// web/src/app/learn/(dashboard)/(routes)/teacher/courses/[courseId]/_components/attachment-form.tsx
'use client';
import React, {useState} from 'react';
import {Course, Attachment} from "@prisma/client";
import * as z from "zod";
import {useRouter} from "next/navigation";
import toast from "react-hot-toast";
import {useGenerateUploadUrl} from "@/features/upload/api/use-generate-upload-url";
import {Button} from "@/components/ui/button";
import {ImageIcon, Pencil, PlusCircle, FileIcon, Loader2, X} from "lucide-react";
import FileUpload from "@/components/learn/file-upload";

interface Props {
    initialData: Course & { attachments: Attachment[] }
    courseId: string
}

const formSchema = z.object({
    url: z.string().min(1)
})

const AttachmentForm = ({initialData, courseId}: Props) => {
    const router = useRouter()

    const [isEditing, setIsEditing] = useState(false)
    const toggleEdit = () => setIsEditing((current) => !current)

    const [deletingId, setDeletingId] = useState<string | null>(null)
    const onDelete = async (id: string) => {
        try {
            setDeletingId(id)
            await fetch(`/api/course/${courseId}/attachments/${id}`, {
                method: 'DELETE'
            })
            toast.success(`Attachment deleted`)
            router.refresh()
        } catch (error) {
            toast.error(`Something went wrong`)
            console.error(error)
        } finally {
            setDeletingId(null)
        }
    }

    const onSubmit = async (values: z.infer<typeof formSchema>) => {
        try {
            const res = await fetch(`/api/course/${courseId}/attachments`, {
                method: "POST",
                body: JSON.stringify(values),
                headers: {
                    "Content-Type": "application/json"
                }
            })
            if (!res.ok) throw new Error(`failed fetch`)
            toast.success(`更新成功`)
            toggleEdit()
            router.refresh()
        } catch (err) {
            toast.error(`Something went wrong`)
            console.error('Something went wrong', err);
        }
    }

    const {mutate: uploadImg, isPending} = useGenerateUploadUrl();

    return (
        <div className={`mt-6 border bg-slate-100 rounded-md p-4`}>
            <div className={`font-medium flex items-center justify-between`}>
                Course attachment
                <Button variant={'ghost'}
                        onClick={toggleEdit}>
                    {isEditing && (
                        <>Cancel</>
                    )}
                    {!isEditing && (
                        <>
                            <PlusCircle className={`size-4 mr-2`}/>
                            Add an file
                        </>
                    )}
                </Button>
            </div>
            {!isEditing && (
                <>
                    {initialData.attachments.length === 0 && (
                        <p className={`text-sm mt-2 text-slate-500 italic`}>
                            No attachments yet
                        </p>
                    )}
                    {initialData.attachments.length > 0 && (
                        <div className={`space-y-2`}>
                            {initialData.attachments.map((attachment) => (
                                <div
                                    key={attachment.id}
                                    className={`flex items-center p-3 w-full bg-sky-100 border-sky-200
                                border text-sky-700 rounded-md`}
                                >
                                    <FileIcon className={`size-4 mr-2 flex-shrink-0`}/>
                                    <p className={`text-xs line-clamp-1`}>{attachment.name}</p>
                                    {deletingId === attachment.id && (
                                        <div className={`ml-auto`}>
                                            <Loader2 className={`size-4 animate-spin`}/>
                                        </div>
                                    )}
                                    {deletingId !== attachment.id && (
                                        <button
                                            onClick={() => onDelete(attachment.id)}
                                            className={`ml-auto hover:opacity-75 transition`}>
                                            <X className={`size-4`}/>
                                        </button>
                                    )}
                                </div>
                            ))}
                        </div>
                    )}
                </>
            )}
            {isEditing && (
                <div>
                    <FileUpload
                        accept={'*/*'}
                        // endpoint={'courseImage'}
                        onChange={async (f) => {
                            if (f) {
                                let url = await uploadImg({
                                    // @ts-ignore
                                    image: f,
                                    prefix: `course/${courseId}/attachments`
                                })
                                if (!url || isPending) return
                                await onSubmit({url: url})
                            }
                        }}
                    />
                    <div className={`text-xs text-muted-foreground mt-4`}>
                        Add anything your students might need to complete the course.
                    </div>
                </div>
            )}
        </div>
    );
};

export default AttachmentForm;